// src/views/Excel/composables/useEventHandlers.ts
import { ref, Ref, onUnmounted } from 'vue';
import type { Cell, Column } from '../types';

export function useEventHandlers(
  tableData: Ref<Cell[][]>,
  columns: Ref<Column[]>,
  selectedCells: Ref<Set<string>>,
  dragState: any,
  isEditing: Ref<boolean>,
  editingCell: Ref<any>,
  editInputValue: Ref<string>,
  clickTimer: Ref<number | null>,
  CLICK_DELAY: number,
  headerScrollLeft: Ref<number>,
  tableWrapper: Ref<HTMLElement | null>,
  columnWidths: Ref<number[]>,
  history: Ref<any>,
  historyIndex: Ref<number>,
  getCellId: Function,
  clearSelection: Function,
  selectCell: Function,
  enterEditMode: Function,
  finishEditing: Function,
  cancelEditing: Function,
  moveSelectedCells: Function,
  endDrag: Function,
  showDragPreviewForSelection: Function,
  saveState: Function,
  undo: Function,
  redo: Function,
  isRowSelected: Function
) {
  // 存储事件监听器引用，以便清理
  let keydownListener: ((e: KeyboardEvent) => void) | null = null;
  let mouseupListener: ((e: MouseEvent) => void) | null = null;

  // 修改 handleScroll 方法
  const handleScroll = () => {
    if (tableWrapper.value) {
      // 更新表头横向滚动位置
      headerScrollLeft.value = tableWrapper.value.scrollLeft;
    }
  };

  /**
   * 角标点击处理
   * @param event
   */
  const handleCornerMouseDown = (event: MouseEvent) => {
    event.preventDefault();
    // 修改为取消选中所有单元格
    clearSelection(selectedCells.value);
  };

  // 单元格点击处理
  const handleCellClick = (event: MouseEvent, rowIndex: number, colIndex: number, disEditing: boolean) => {
    event.stopPropagation();

    if (dragState.isDragging) return;
    // 如果正在编辑状态且点击的不是当前编辑的单元格，则取消编辑
    if (isEditing.value && (editingCell.value.row !== rowIndex || editingCell.value.col !== colIndex)) {
      finishEditing(isEditing, editingCell, editInputValue, tableData, saveState);
    }

    // 清除已存在的定时器
    if (clickTimer.value) {
      clearTimeout(clickTimer.value);
      clickTimer.value = null;
      if (!disEditing) return;
      // 双击处理 - 进入编辑模式
      enterEditMode(rowIndex, colIndex, selectedCells, clearSelection, isEditing, editingCell, tableData, editInputValue, getCellId);
      return;
    }

    // 设置单击定时器
    clickTimer.value = window.setTimeout(() => {
      // 单击处理 - 选择单元格
      if (!event.ctrlKey && !event.shiftKey) {
        selectCell(rowIndex, colIndex, selectedCells.value);
      } else if (event.ctrlKey) {
        const cellId = getCellId(rowIndex, colIndex);
        if (selectedCells.value.has(cellId)) {
          selectedCells.value.delete(cellId);
        } else {
          selectedCells.value.add(cellId);
        }
      }
      clickTimer.value = null;
    }, CLICK_DELAY);
  };

  const handleTableClick = (event: MouseEvent) => {
    const target = event.target as HTMLElement;
    if (target.classList.contains('table-wrapper') || target.tagName === 'TABLE') {
      clearSelection(selectedCells.value);
    }
  };

  // 键盘事件处理 - 修改为全局监听
  const handleKeyDown = (event: KeyboardEvent) => {
    // 检查事件是否源自当前表格组件
    if (!tableWrapper.value?.contains(event.target as Node)) return;
    // 如果正在编辑，不处理快捷键
    if (isEditing.value) return;

    // Ctrl + Z 撤销
    if (event.ctrlKey && event.key === 'z') {
      event.preventDefault();
      if (historyIndex.value > 0) {
        handleUndo();
      }
    }

    // Ctrl + Y 重做
    if (event.ctrlKey && event.key === 'y') {
      event.preventDefault();
      if (history.value && historyIndex.value < history.value.length - 1) {
        handleRedo();
      }
    }

    // Delete 键删除选中内容
    if (event.key === 'Delete' && selectedCells.value.size > 0) {
      event.preventDefault();
      // 这里需要传入 deleteSelected 函数
    }

    // Escape 键取消选择
    if (event.key === 'Escape') {
      event.preventDefault();
      clearSelection(selectedCells.value);
    }
  };

  const handleCellMouseDownWrapper = (event: MouseEvent, rowIndex: number, colIndex: number) => {
    // 注意：这里需要传入 handleCellMouseDown 函数
    // handleCellMouseDown(event, rowIndex, colIndex, tableData.value, selectedCells.value, getCellId);
    // 如果是移动单元格模式，显示预览
    if (dragState.isMovingCells) {
      showDragPreviewForSelection(tableWrapper.value);
    }
  };

  const handleMouseMoveWrapper = (event: MouseEvent) => {
    // 注意：这里需要传入 handleMouseMove 函数
    // handleMouseMove(event, tableData.value, columns.value, tableWrapper.value, selectedCells.value, getCellId);
  };

  const handleMouseUp = () => {
    if (dragState.isMovingCells && dragState.moveTarget.row >= 0 && dragState.moveTarget.col >= 0) {
      const success = moveSelectedCells(dragState.moveTarget.row, dragState.moveTarget.col, tableData.value);

      if (success) {
        // 可以选择是否清空选中状态，或者选中移动后的区域
        const { minRow, maxRow, minCol, maxCol } = dragState.dragDataRange;
        const rowsCount = maxRow - minRow + 1;
        const colsCount = maxCol - minCol + 1;
        // 清空当前选中
        clearSelection(selectedCells.value);

        // 选中移动后的新区域
        for (let r = dragState.moveTarget.row; r < dragState.moveTarget.row + rowsCount; r++) {
          for (let c = dragState.moveTarget.col; c < dragState.moveTarget.col + colsCount; c++) {
            selectedCells.value.add(getCellId(r, c));
          }
        }

        // 视觉反馈
        const previewElement = document.querySelector('.drag-preview');
        if (previewElement) {
          previewElement.classList.add('drag-success');
          setTimeout(() => {
            previewElement.classList.remove('drag-success');
          }, 300);
        }
      }
    }

    endDrag(tableWrapper.value);
  };

  const finishEditingHandler = () => {
    finishEditing(isEditing, editingCell, editInputValue, tableData, saveState);
  };

  const cancelEditingHandler = () => {
    cancelEditing(isEditing, editingCell);
  };

  // 添加适配函数
  const isRowSelectedAdapted = (row: number): boolean => {
    return isRowSelected(row, columns.value, selectedCells.value, getCellId);
  };

  const isCellSelectedAdapted = (row: number, col: number): boolean => {
    return selectedCells.value.has(getCellId(row, col));
  };

  // 在需要使用 undo/redo 的地方正确传参
  const handleUndo = () => {
    undo(clearSelection, selectedCells);
  };

  const handleRedo = () => {
    redo(clearSelection, selectedCells);
  };

  // 获取指定列的宽度
  const getColumnWidth = (colIndex: number): number => {
    return columnWidths.value[colIndex] || 100; // 默认100px
  };

  // 添加事件监听器
  const addEventListeners = () => {
    // 添加键盘事件监听器
    keydownListener = (event: KeyboardEvent) => handleKeyDown(event);
    document.addEventListener('keydown', keydownListener);

    // 添加鼠标释放事件监听器
    mouseupListener = () => handleMouseUp();
    document.addEventListener('mouseup', mouseupListener);
  };

  // 移除事件监听器
  const removeEventListeners = () => {
    if (keydownListener) {
      document.removeEventListener('keydown', keydownListener);
      keydownListener = null;
    }

    if (mouseupListener) {
      document.removeEventListener('mouseup', mouseupListener);
      mouseupListener = null;
    }
  };

  // 清理函数 - 在组件销毁时调用
  const cleanup = () => {
    removeEventListeners();

    // 清理定时器
    if (clickTimer.value) {
      clearTimeout(clickTimer.value);
      clickTimer.value = null;
    }
  };

  return {
    handleScroll,
    handleCornerMouseDown,
    handleCellClick,
    handleTableClick,
    handleKeyDown,
    handleCellMouseDownWrapper,
    handleMouseMoveWrapper,
    handleMouseUp,
    finishEditingHandler,
    cancelEditingHandler,
    isRowSelectedAdapted,
    isCellSelectedAdapted,
    handleUndo,
    handleRedo,
    getColumnWidth,
    addEventListeners, // 添加事件监听器的方法
    removeEventListeners, // 移除事件监听器的方法
    cleanup // 导出清理函数
  };
}
